﻿using System;
using System.Web.UI;
using ElevatorSpeeches.Framework;
using System.Web;

namespace ElevatorSpeeches.UI.WebForms.Controls
{
    /// <summary>
    /// A control that creates a speech for the logged in user.
    /// 
    /// TODO: Control does not display is a user is not logged in.
    /// </summary>
    public partial class CreateSpeech : UserControl
    {

        /// <summary>
        /// Gets or sets the topic, stored in ViewState
        /// </summary>
        /// <value>The topic.</value>
        public SpeechTopic Topic
        {
            get
            {
                if (ViewState["Topic"] != null)
                    return ((SpeechTopic) ViewState["Topic"]);

                return null;
            }
            set
            {
                ViewState["Topic"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext.Current.Response.Write(HttpContext.Current.User.Identity.Name);
        }

        /// <summary>
        /// Adds the speech button on click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void AddSpeechButtonOnClick(object sender, EventArgs e)
        {
            Speech speech = new Speech { 
                Topic = this.Topic, 
                Body = Body.Text, 
                ExtendedBody = ExtendedBody.Text, 
                User = Utilities.GetCurrentUser()};

            if (speech.IsValid())
            {
                speech.Save();
                Response.Redirect(Utilities.GetSpeechTopicUrl(this.Topic.PrettyUrl));
            }
            else
            {
                ValidationDisplay.ErrorMessages = speech.AllErrorMessages;
            }
        }
    }
}